package utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class ShareImage {
    /**
     * 微信7.0版本号，兼容处理微信7.0版本分享到朋友圈不支持多图片的问题
     */
    private static final int VERSION_CODE_FOR_WEI_XIN_VER7 = 1380;
    /**
     * 微信包名
     */
    public static final String PACKAGE_NAME_WEI_XIN = "com.tencent.mm";


    //判断是否安装微信
    private static boolean isInstallWeChat(Context context) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo("com.tencent.mm", 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null)
            return false;
        else
            return true;

    }

    //分享图片到微信,分享的是本地图片
    public static void shareImagesToWeiXin(Context context, String path) {
        if (!isInstallWeChat(context.getApplicationContext())) {
           // ToastUtils.showToast(context.getApplicationContext(),"沒有安裝微信");
            Toast.makeText(context.getApplicationContext(),"沒有安裝微信",Toast.LENGTH_LONG).show();
            return;
        }
        try {
            Intent weChatIntent = new Intent();
            //com.tencent.mm.ui.tools.ShareImgUI  是分享到微信好友,//com.tencent.mm.ui.tools.ShareToTimeLineUI  是分享到微信朋友圈，最多可以分享九张图片到微信朋友圈
            weChatIntent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI"));
            weChatIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
            ArrayList<Uri> imageList = new ArrayList();
            File[] files = new File(path).listFiles();
            if (files != null) {
                for (File file : files) {
                 //   L.e(file.getAbsolutePath());
                    File f = new File(file.getAbsolutePath());
                    if (f.exists()) {
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {//android 7.0以下
                            imageList.add(Uri.fromFile(f));
                        } else {//android 7.0及以上
                            Uri uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(context.getContentResolver(), f.getAbsolutePath(), f.getName(), null));
                            imageList.add(uri);
                        }
                    }
                }
            }
            weChatIntent.setType("image/*");
            weChatIntent.putExtra(Intent.EXTRA_STREAM, imageList);
//            weChatIntent.putExtra("Kdescription", "aaaa"); //分享描述
            context.startActivity(weChatIntent);
        } catch (Exception e) {
            Toast.makeText(context.getApplicationContext(),"分享失败",Toast.LENGTH_LONG).show();
           // ToastUtils.showToast(context.getApplicationContext(),"分享失败");
        }
    }

    /**
     * 获取制定包名应用的版本的versionCode
     * @param context
     * @param
     * @return
     */
    public static int getVersionCode(Context context,String packageName) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(packageName, 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static void shareImageToWechat(Bitmap bmp, String content,Context mContext) {
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
        String fileName = "share";
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ArrayList<Uri> uris = new ArrayList<>();
        Uri uri = null;
        try {
            ApplicationInfo applicationInfo = mContext.getApplicationInfo();
            int targetSDK = applicationInfo.targetSdkVersion;
            if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(mContext.getContentResolver(), currentFile.getAbsolutePath(), fileName, null));
            } else {
                uri = Uri.fromFile(new File(currentFile.getPath()));
            }
            uris.add(uri);
        } catch (Exception ex) {

        }
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        ComponentName comp = new ComponentName(PACKAGE_NAME_WEI_XIN, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        intent.setComponent(comp);
        intent.setType("image/*");
        intent.putExtra("Kdescription", content);
        if ( getVersionCode(mContext,PACKAGE_NAME_WEI_XIN) < VERSION_CODE_FOR_WEI_XIN_VER7) {
            // 微信7.0以下版本
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        } else {
            // 微信7.0及以上版本
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_STREAM, uri);
        }
        mContext.startActivity(intent);
    }




}